<template>
  <div class="dataTarget">
    <el-divider content-position="left">
      <i></i>数据来源
    </el-divider>
    <el-form ref="form" :model="dataTarget" label-width="120px" :rules="formRules">
      <el-form-item label="数据库类型" prop="databaseType">
        <el-select v-model="dataTarget.databaseType" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseTypeEvent()">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="database">
        <el-select v-model="dataTarget.database" clearable filterable placeholder="请选择" style="width: 220px">
          <el-option v-for="item in databaseOptions" :key="item.id" :label="item.datasourceName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <div>
        <el-divider content-position="left">
          <i></i>字段列表
        </el-divider>
        <div class="tableBox">
          <znxd-list-modify v-model="dataTarget.writeToDataSources" :formColumn="formColumn" :initData="tablesData"></znxd-list-modify>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import { deepCopy } from "@/utils/data.js";
import { typeGetDataSource } from "@/api/dataset/database.js";
import { selectDictionaryByType } from "@/api/dict";
// import { getTables } from "@/api/dataset/table.js";

export default {
  components: {},
  data() {
    return {
      formRules: {
        databaseType: [{ required: true, message: "不能为空" }],
        database: [{ required: true, message: "不能为空" }]
      },
      dataTarget: {
        databaseType: null,
        database: null
      },
      // 数据库类型字典
      typeOptions: [
        // {
        //   label: "mysql",
        //   value: "mysql"
        // },
        // {
        //   label: "oracle",
        //   value: "oracle"
        // },
        // {
        //   label: "sqlserver",
        //   value: "sqlserver"
        // },
        // {
        //   label: "postgresql",
        //   value: "postgresql"
        // },
        // {
        //   label: "dm",
        //   value: "dm"
        // }
      ],
      updataWayOptions: [
        {
          label: "数据追加",
          value: 0
        },
        {
          label: "数据覆盖",
          value: 1
        }
      ],
      databaseOptions: [],
      // 多表
      tablesData: [],
      formColumn: [
        // {
        //   name: "tableName",
        //   label: "原表",
        //   type: "label"
        // },
        // {
        //   name: "tableName",
        //   label: "目标表",
        //   type: "input"
        // },
        // {
        //   init: "自动创建",
        //   label: "目标表建立方式",
        //   type: "label"
        // },
        // {
        //   name: "updateWay",
        //   label: "更新方式",
        //   type: "select",
        //   options: this.updataWayOptions
        // }
      ]
    };
  },
  props: {
    initData: Object,
    mode: String,
    dataSource: Array
  },
  watch: {
    dataTarget: {
      deep: true,
      handler: function (val) {
        // console.log("dataTarget", val);
        this.$emit("input", val);
      }
    },
    initData: {
      deep: true,
      handler: async function (obj) {
        // this.$refs.form.resetFields();
        this.dataTarget.databaseType = obj.writerDatabaseType;
        this.dataTarget.database = obj.writerDataSourceId;
        this.chooseTypeEvent();
        // this.chooseDatabaseEvent();
        // this.tablesData = obj.writeToDataSources || [];
        this.tablesData = deepCopy(obj.writeToDataSources);
        let _this = this;
        setTimeout(function () {
          _this.$refs.form.clearValidate(); // 消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        }, 30);
      }
    },
    dataSource: {
      deep: true,
      handler: function (val) {
        // this.$refs.form.resetFields();
        // console.log("this.tablesData", this.tablesData)
        let arrayData = [...this.tablesData];
        val.map((x) => {
          // 增量更新
          let filters = this.tablesData.filter((d) => {
            return d.readerName === x.ruleName;
          });
          // console.log("filters", filters.length)
          if (filters.length === 0) {
            arrayData.push({
              datasourceId: x.id,
              readerName: x.ruleName,
              writerTable: x.ruleName,
              isCreateTable: 1,
              updateWay: 0
            });
          }
        });
        // this.tablesData = arrayData;
        // if (this.tablesData.length === 0 || this.dataSource.length !== this.tablesData.length) {
        //   let arrayData = [...this.tablesData];
        //   val.map(x => {
        //     if (this.tablesData.filter(d => { return d.readerName === x.readerName }).length <= 0) {
        //       arrayData.push({
        //         datasourceId: x.id,
        //         readerName: x.ruleName,
        //         writerTable: x.ruleName,
        //         isCreateTable: 1,
        //         updateWay: 0
        //       })
        //     }
        //   })
        this.tablesData = arrayData;
        // }
      }
    }
  },
  methods: {
    chooseTypeEvent() {
      if (!this.dataTarget.databaseType) {
        return;
      }
      let obj = {
        tableType: this.dataTarget.databaseType
      };
      typeGetDataSource(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.databaseOptions = data.content;
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    // chooseDatabaseEvent() {
    //   if (!this.dataTarget.database) { return }
    //   let obj = {
    //     datasourceId: this.dataTarget.database
    //   };
    //   getTables(obj).then((res) => {
    //     let data = res.data;
    //     if (data.code === 200) {
    //       this.tableOptions = data.content;
    //       // if (isFirst) {
    //       //   this.tablesData = [];
    //       // }
    //     } else {
    //       this.$message({
    //         message: data.msg,
    //         type: "error"
    //       });
    //     }
    //   });
    // },
    // 校验数据
    validateForm() {
      let flag = true;
      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });

      if (this.dataTarget.writeToDataSources.length === 0) {
        this.$message({
          message: "数据库表不能为空",
          type: "error"
        });
        flag = false;
        return flag;
      }

      return flag;
    },
    // import { selectDictionaryByType } from "@/api/dict";
    getDBType() {
      selectDictionaryByType({ type: "dbType" })
        .then((res) => {
          let data = res.data;
          if (data.code === 200) {
            let options = [];
            data.data.map((x) => {
              options.push({ label: x.value, value: x.value });
            });
            this.typeOptions = options;
            // this.initFormColumn();
          } else {
            // this.$message.error(data.msg);
          }
        })
        .catch(() => {
          // this.$message.error("操作失败");
        });
    },
    initForm() {
      this.formColumn = [
        {
          name: "readerName",
          label: "规则名称",
          type: "label"
        },
        {
          name: "writerTable",
          label: "目标表",
          type: "input"
        },
        {
          init: "自动创建",
          label: "目标表建立方式",
          type: "label"
        },
        {
          name: "updateWay",
          label: "更新方式",
          type: "select",
          options: this.updataWayOptions
        }
      ];
    }
  },
  mounted() {
    this.getDBType();
    this.initForm();
  }
};
</script>
<style lang="scss" scoped>
.dataTarget {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
}
</style>
